package cn.sell.admin.sys.menu;

import cn.sell.comm.model.qo.PageQO;
import cn.sell.comm.model.vo.PageVO;
import cn.sell.comm.result.annotation.ResponseResult;
import cn.sell.mbg.sys.menu.UmsMenu;
import cn.sell.mbg.sys.menu.service.UmsMenuService;
import cn.sell.mbg.sys.menu.view.UmsMenuWithChildrenItem;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Log4j2
@RestController
@ResponseResult
@RequestMapping("/rest/menu")
@Api(tags = "MenuController - 权限菜单管理")
@ApiResponses({
        @ApiResponse(code = 200, message = "请求正常"),
        @ApiResponse(code = 4001, message = "系统异常")
})
public class MenuController {

    @Autowired
    public UmsMenuService umsMenuService;

    @ApiOperation("新增菜单")
    @PostMapping("/create")
    public Long create(@RequestBody UmsMenu umsMenu) throws Exception {
        Assert.notNull(umsMenu.getName(), "name is not null [ 前端名称不能为空 ]");
        Assert.notNull(umsMenu.getSort(), "sort is not null [ 排序不能为空 ]");
        Assert.notNull(umsMenu.getTitle(), "title is not null [ 菜单名称不能为空 ]");
        Assert.notNull(umsMenu.getParentId(), "parentId is not null [ 上级菜单id不能为空 ]");
        return umsMenuService.insert(umsMenu);
    }

    @ApiOperation("删除菜单")
    @GetMapping("/delete/{id}")
    public int delete(@PathVariable("id") Long id) {
        Assert.notNull(id, "id is not null [ 菜单id不能为空 ]");
        return umsMenuService.deleteByPk(id);
    }

    @ApiOperation("更新菜单")
    @PostMapping("/update")
    public int update(@RequestBody UmsMenu umsMenu) {
        Assert.notNull(umsMenu.getId(), "id is not null [ 菜单id不能为空 ]");
        return umsMenuService.updateByPkSelective(umsMenu.getId(), umsMenu);
    }

    @ApiOperation("根据父级id查询菜单列表")
    @GetMapping("/list/{parentId}")
    public PageVO<UmsMenu> list(@PathVariable("parentId") Long parentId,
                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Assert.notNull(parentId, "id is not null [ 上级菜单id不能为空 ]");
        UmsMenu umsMenu = new UmsMenu();
        umsMenu.setParentId(parentId);
        PageQO pageQO = new PageQO(pageNum, pageSize);
        pageQO.setCondition(umsMenu);
        return umsMenuService.selectPage(pageQO);
    }

    /**
     * 列出菜单分类
     *
     * @return
     */
    @ApiOperation("返回所有菜单，tree")
    @GetMapping("/tree")
    public List<UmsMenuWithChildrenItem> tree() {
        return umsMenuService.getMenu();
    }

}
